package com.jy.app.lib.utils;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PermissionGroupInfo;
import android.content.pm.PermissionInfo;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;

import com.jy.app.lib.application.BaseApplication;

import java.io.File;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.Locale;

/**
 * Created by ZHANG on 2016/3/19.
 */
public class DeviceUtil {

    /**
     * 获取系统当前语言
     * @return
     */
    public static String getLanguage(){
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取系统当前区域
     * @return
     */
    public static String getCountry(){
        return Locale.getDefault().getCountry();
    }

    /**
     * 设备的唯一ID（GSM手机的 IMEI 和 CDMA手机的 MEID）
     * @return
     */
    public static String getMEID(Context context){
        TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

    /**
     * 获取应用的版本号
     * @return
     */
    public static String getVersionName(Context context){
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(),0);
            return pi.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            LogUtil.e(e.getMessage(), e);
            return "1.0.0";
        }
    }

    /**
     * 获取应用的版本号
     * @return
     */
    public static int getVersionCode(Context context){
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(),0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            LogUtil.e(e.getMessage(), e);
            return 0;
        }
    }

    /**
     * 获取应用的版本号
     * @return
     */
    public static String getDeviceBrand(){
        return Build.BRAND;
    }

    /**
     * 获取应用的版本号
     * @return
     */
    public static String getDeviceModel(){
        return Build.MODEL;
    }

    /**
     * 获取操作系统版本号
     * @return
     */
    public static String getOS(){
        return Build.VERSION.RELEASE;
    }

    /**
     * 安装apk
     * @return
     */
    public static void installApk(Context context, String path){
        File file = new File(path);
        if(file.exists() && file.getName().toLowerCase().endsWith(".apk")){
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            context.startActivity(intent);
            ActivityUtil.getInstance().AppExit(context);
        }
    }



    /**
     * 获取手机运营商
     * @param context
     * @return
     */
    public static String getNetworkOperators(Context context) {
        String strOperators = "unknown";
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        // 返回唯一的用户ID;就是这张卡的编号神马的
        String IMSI = telephonyManager.getSubscriberId();
        // IMSI号前面3位460是国家，紧接着后面2位00 02是中国移动，01是中国联通，03是中国电信。
        if (IMSI != null) {
            if (IMSI.equals("46000") || IMSI.equals("46002") || IMSI.equals("46007")) {
                strOperators = "中国移动";
            } else if (IMSI.equals("46001")) {
                strOperators = "中国联通";
            } else if (IMSI.equals("46003")) {
                strOperators = "中国电信";
            }
        }
        return strOperators;
    }
    /**
     * 获取网络类型
     * @param context
     * @return
     */
    public static String getNetworkType(Context context) {
        String strNetworkType = "unknown";
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo == null) {
            return strNetworkType;
        }
        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            strNetworkType = "WIFI";
        } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            switch (networkInfo.getSubtype()) {
                case TelephonyManager.NETWORK_TYPE_CDMA:// 网络类型为CDMA
                case TelephonyManager.NETWORK_TYPE_EDGE:// 网络类型为EDGE
                case TelephonyManager.NETWORK_TYPE_GPRS:// 网络类型为GPRS
                    strNetworkType = "2G";
                    break;
                case TelephonyManager.NETWORK_TYPE_EVDO_0:// 网络类型为EVDO0
                case TelephonyManager.NETWORK_TYPE_EVDO_A:// 网络类型为EVDOA
                case TelephonyManager.NETWORK_TYPE_HSDPA:// 网络类型为HSDPA
                case TelephonyManager.NETWORK_TYPE_HSPA:// 网络类型为HSPA
                case TelephonyManager.NETWORK_TYPE_HSUPA:// 网络类型为HSUPA
                case TelephonyManager.NETWORK_TYPE_UMTS:// 网络类型为UMTS
                    strNetworkType = "3G";
                    break;
                default:
                    break;
            }
        }
        return strNetworkType;
    }

    /**
     * 获取当前手机号码
     * @param context
     * @return
     */
    public static String getNativePhoneNumber(Context context) {
        String NativePhoneNumber = "";
        TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        NativePhoneNumber = telephonyManager.getLine1Number();
        return NativePhoneNumber;
    }

    /**
     * 获取手机屏幕宽度
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.widthPixels;
    }

    /**
     * 获取手机屏幕高度
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return dm.heightPixels;
    }

    /**
     *  获取手机状态栏的高度
     * @param activity
     * @return
     */
    public static int getScreenStatusBarHeight(Activity activity) {
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);// /取得整个视图部分,注意，如果你要设置标题样式，这个必须出现在标题样式之后，否则会出错
        int screenWidth = frame.width();
        int screenHeight = frame.height();
        // 状态栏的高度，所以frame.height,frame.width分别是系统的高度的宽度
        int statusBarHeight = frame.top;

        View v = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT);// /获得根视图
        // 状态栏标题栏的总高度/ statusBarHeight是上面所求的状态栏的高度
        int contentTop = v.getTop();
        // 所以标题栏的高度为contentTop-statusBarHeight
        int titleBarHeight = contentTop - statusBarHeight;
        // 视图区域可以使用的宽度
        int realViewWidth = v.getWidth();
        // 视图的高度，不包括状态栏和标题栏
        int realViewHeight = v.getHeight();
        String strDeviceSizeInfo = "屏幕宽度" + screenWidth + "\n" + "屏幕高度" + screenHeight + "\n" + "状态栏高度" + statusBarHeight + "\n" + "标题栏高度" + titleBarHeight + "\n" + "可用宽度" + realViewWidth + "\n" + "可用高度（不含状态栏和标题栏）" + realViewHeight;

        LogUtil.i(strDeviceSizeInfo);
        return statusBarHeight;
    }

    /**
     * 检测手机sim卡是否可用
     * @return
     */
    public static boolean isSimActive() {
        TelephonyManager tm = (TelephonyManager) BaseApplication.appContext.getSystemService(Context.TELEPHONY_SERVICE);
        if (tm == null) {
            return false;
        }
        return TelephonyManager.SIM_STATE_READY == tm.getSimState();
    }

    /**
     * 检测手机是否为横屏
     * @param context
     * @return
     */
    public static boolean getLandscapeDevice(Context context) {
        Activity activity = (Activity) context;
        int orientation = activity.getResources().getConfiguration().orientation;
        int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        return (orientation == Configuration.ORIENTATION_PORTRAIT && displayRotation % 2 != 0) || (orientation == Configuration.ORIENTATION_LANDSCAPE && displayRotation % 2 == 0);
    }

    /**
     * 获取包信息
     * @param context
     * @return
     */
    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo info = null;
        try {
            info = context.getPackageManager().getPackageInfo(getAppPackageName(context), 0);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        if (info == null)
            info = new PackageInfo();
        return info;
    }

    /**
     * 获取app包名
     * @param context
     * @return
     */
    public static String getAppPackageName(Context context) {
        return context.getPackageName();
    }

    /**
     * 获取当前手机的ip
     * @param context
     * @return
     */
    public static String getPhoneIP(Context context) {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        // if (!inetAddress.isLoopbackAddress() && inetAddress
                        // instanceof Inet6Address) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (Exception e) {
        }
        return "";
    }

    /**
     * 获取当前手机的mac地址
     * @param context
     * @return
     */
    public static String getMacAddress(Context context) {
        // 获取mac地址：
        String macAddress = "000000000000";
        try {
            WifiManager wifiMgr = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
            if (null != info) {
                if (!TextUtils.isEmpty(info.getMacAddress())) {
                    macAddress = info.getMacAddress();
                }
            }
        } catch (Exception e) {
            LogUtil.e(e.getMessage(), e);
            return macAddress;
        }
        return macAddress;
    }
    /**
     * 获取手机音频的播放模式
     * @param context
     * @param boolCallIn
     */
    public static void setAudioMode(Context context, boolean boolCallIn) {
        try {
            AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
            if (boolCallIn) {
                audioManager.setSpeakerphoneOn(true);// 关闭扬声器
                audioManager.setMode(AudioManager.MODE_NORMAL);// 把模式调成正常放音模式
            } else {
                LogUtil.i("听筒放音模式");
                audioManager.setSpeakerphoneOn(true);// 关闭扬声器
                audioManager.setMode(AudioManager.MODE_IN_CALL);// 把模式调成听筒放音模式
            }
        } catch (Exception e) {
            LogUtil.e("Could'nt retrieve permissions for package",e);
        }
    }

    /**
     * 检查音频是否正常
     * @return
     */
    public static boolean isAudioNormal() {
        AudioManager mAudioManager = (AudioManager) BaseApplication.appContext.getSystemService(Context.AUDIO_SERVICE);
        return mAudioManager.getRingerMode() == AudioManager.RINGER_MODE_NORMAL;
    }


    /**
     * 检测SD卡是否存在并给予提示
     * @param context
     * @param msg
     * @return
     */
    public static boolean checkAndToastWhenSdcardNotExists(Context context, String msg) {
        boolean exists = FileUtils.isSDExist();
        if (!exists) {
            ToastUtils.toastLong(context, msg);
        }

        return exists;
    }

    /**
     * 查看应用的权限
     * @param context
     */
    public static void getAppPermisson(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            // 得到自己的包名
            String pkgName = pi.packageName;

            PackageInfo pkgInfo = pm.getPackageInfo(pkgName, PackageManager.GET_PERMISSIONS);// 通过包名，返回包信息
            String sharedPkgList[] = pkgInfo.requestedPermissions;// 得到权限列表

            for (int i = 0; i < sharedPkgList.length; i++) {
                String permName = sharedPkgList[i];

                PermissionInfo tmpPermInfo = pm.getPermissionInfo(permName, 0);// 通过permName得到该权限的详细信息
                PermissionGroupInfo pgi = pm.getPermissionGroupInfo(tmpPermInfo.group, 0);// 权限分为不同的群组，通过权限名，我们得到该权限属于什么类型的权限。
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append(i + "-" + permName + "\n");
                stringBuffer.append(i + "-" + pgi.loadLabel(pm).toString() + "\n");
                stringBuffer.append(i + "-" + tmpPermInfo.loadLabel(pm).toString() + "\n");
                stringBuffer.append(i + "-" + tmpPermInfo.loadDescription(pm).toString() + "\n");
                stringBuffer.append(i + "- end" + "\n");
                LogUtil.i("getAppPermisson:"+ stringBuffer.toString());
            }
        } catch (Exception e) {
            LogUtil.e("Could'nt retrieve permissions for package",e);
        }
    }



    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     * @param context
     * @return true 表示开启
     */
    public static final boolean isOpenGps(final Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    /**
     * 强制帮用户打开GPS
     * @param context
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

}
